package org.example.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.example.pojo.Result;
import org.example.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

@RestController
@Tag(name = "上传文件", description = "上传文件")
@RequestMapping("/file")
public class FileUploadController {
    @Value("${file.prefix}")
    private String prefix;
    @Value("${file.path}")
    private String path;

    @PostMapping(value = "/uploadAliOss", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Operation(summary = "上传文件", description = "上传文件")
    public Result<String> uploadAliOss(@RequestPart MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
//        file.transferTo(new File("D:\\workspace\\" + fileName));
        String url = AliOssUtil.uploadFile( fileName, file.getInputStream());

        return Result.success(url);
    }

    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Operation(summary = "上传文件", description = "上传文件")
    public Result<String> upload(@RequestPart MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String date = formatter.format(Calendar.getInstance().getTime());
        String fileName = date + '/' + UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));

        File folder = new File(path + "/" + date);
        folder.mkdirs();

        file.transferTo(new File(path + "/" + fileName));

        return Result.success(prefix + '/' + fileName);
    }
}
